package com.quad.innovators.salesease.common.utils;

import com.quad.innovators.salesease.constants.SystemConstants;
import com.quad.innovators.salesease.context.UserContext;
import com.quad.innovators.salesease.model.dto.SysUserAuthInfo;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Spring Security 工具类
 *
 */
public class SecurityUtils {

    public static Long getUserId() {
        return UserContext.getCurrentUser().getUserId();
    }

    public static String getUsername(){
        return UserContext.getCurrentUser().getUsername();
    }

    public static Integer getDataPermissions(String permissionCode, List<Map<String, Integer>> roleDataScopeList) {
        int dataPermissions = Integer.MAX_VALUE;
        for (Map<String, Integer> maps : roleDataScopeList) {
            if(maps.get(permissionCode) != null) {
                dataPermissions = Math.min(dataPermissions, maps.get(permissionCode));
            }
        }
        return dataPermissions;
    }

    /**
     * 获取用户角色集合
     *
     * @return 角色集合
     */
    public static Set<String> getRoles() {
        SysUserAuthInfo currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
           return currentUser.getRoles();
        }
        return Collections.EMPTY_SET;
    }

    /**
     * 是否超级管理员
     * <p>
     * 超级管理员忽视任何权限判断
     */
    public static boolean isRoot() {
        Set<String> roles = getRoles();
        return roles.contains(SystemConstants.ROOT_ROLE_CODE);
    }

}
